﻿#region

using System;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevLib.ExtensionMethods;
using DevLib.ModernUI.Forms;
using Flurl.Http;
using LocalNugetUpdate.BAL.Mehtod;
using LocalNugetUpdate.Model;
using Newtonsoft.Json;
using wsy.ext.Devlib.ExtensionMethods;
using wsy.ext.flurl.http;

#endregion

namespace LocalNugetUpdate
{
    public partial class Form1 : ModernForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string Floderpath { get; set; }
        private bool IsDownloaded { get; set; }

        public async void Form1_Load(object sender, EventArgs e)
        {
            IsDownloaded = false;
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowDialog();
            if (fbd.SelectedPath.IsNullOrEmpty())
                Environment.Exit(0);
            Floderpath = fbd.SelectedPath;
            modernButton1.Enabled = false;
            modernButton2.Enabled = false;
            var nfo = (await new GetNupkgInfo(Floderpath).GetPackages()).MMetadatas;
            modernDataGridView1.DataSource = ConfigDataShowClass.ConvertDataShowModels(nfo);
            int cols = modernDataGridView1.Columns.Count;
            modernDataGridView1.Columns[cols - 1].Visible = false;
            modernButton1.Enabled = true;
            modernButton2.Enabled = true;
        }

        private async void modernButton1_Click(object sender, EventArgs e)
        {
            
            timer1.Enabled = true;
            modernButton1.Enabled = false;
            modernButton2.Enabled = false;
            if (IsDownloaded)
            {
                var nfo = (await new GetNupkgInfo(Floderpath).GetPackages()).MMetadatas;
                modernDataGridView1.DataSource = ConfigDataShowClass.ConvertDataShowModels(nfo);
                int cols = modernDataGridView1.Columns.Count;
                modernDataGridView1.Columns[cols - 1].Visible = false;
            }
            IsDownloaded = false;
            var src = (BindingList<DataShowModel>) modernDataGridView1.DataSource;
            await src.TasksEachDo(CheckOne, 10);
            modernButton1.Enabled = true;
            modernButton2.Enabled = true;
            BeginInvoke(new Action((() => { modernDataGridView1.Refresh(); })));
            timer1.Enabled = false;
        }


        private async Task CheckOne(DataShowModel src)
        {
            if (src.State == "检查完毕")
                return;
            src.State = "检查中";
            string tRes;
            try
            {
                tRes = await $"https://api-v2v3search-0.nuget.org/query?q={src.Id}&skip=0&take=30&prerelease=true"
                    .WithTimeout(5)
                    .GetStringAsync();
            }
            catch (Exception)
            {
                src.State = "检查超时";
                return;
            }
            ResJsonModel res = JsonConvert.DeserializeObject<ResJsonModel>(tRes);
            var listdata = res.Data;
            var data = listdata.FirstOrDefault(s => s.Id.ToLower() == src.Id.ToLower());

            if (data != null)
            {
                src.LastVersion = data.Version;
                if (!src.Versions.Contains(data.Version))
                {
                    src.PreUpdate = true;
                    src.JsonUrl = data.JsonUrl;
                }
                src.State = "检查完毕";
            }
            else
            {
                src.State = "未发现";
            }
        }

        private async void modernButton2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            modernButton1.Enabled = false;
            modernButton2.Enabled = false;
            var src = ((BindingList<DataShowModel>) modernDataGridView1.DataSource).Where(s => s.PreUpdate).ToList();
            await src.TasksEachDo(DownNupkg, 2);
            modernButton1.Enabled = true;
            modernButton2.Enabled = true;
            BeginInvoke(new Action((() => { modernDataGridView1.Refresh(); })));
            timer1.Enabled = false;
            IsDownloaded = true;
        }

        private async Task DownNupkg(DataShowModel src)
        {
            src.State = "获取下载地址";
            nupkgJsonModel nupkg = null;
            try
            {
                nupkg = await src.JsonUrl.WithTimeout(5).GetJsonAsync<nupkgJsonModel>();
            }
            catch (Exception)
            {
                src.State = "下载地址解析超时";
                return;
            }
            if (nupkg == null)
            {
                src.State = "下载地址解析超时";
                return;
            }

            string url = null;
            foreach (nupkgJsonModel.Item nupkgItem in nupkg.Items)
            {
                var it = nupkgItem.Items?.FirstOrDefault(s => s.CatalogEntry.Version == src.LastVersion);
                if (it == null)
                    continue;
                url = it.CatalogEntry.PackageContent;
            }
            if (url == null)
            {
                src.State = "下载地址解析失败";
                return;
            }
            src.State = "开始下载";
            try
            {
                bool isFinished = await url.WithTimeout(30).DownloadFileAsync(Floderpath,
                    new Progress<DownloadFileProgressInfo>(
                        s =>{
                            src.State = $"{s.TotalDataSize} / {s.FinalDataSize} ";
                        }));
            }
            catch (Exception ex)
            {
                src.State = "下载失败";
                return;
            }
            src.PreUpdate = false;
            src.State += "下载完毕";
            await Task.Delay(50);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            BeginInvoke(new Action((() => { modernDataGridView1.Refresh(); })));
        }
    }
}